package com.example.back.service.impl;

import java.util.Map;
import java.util.stream.Collectors;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.annotation.Resource;

import com.example.back.dto.ExcelOrderDrug;
import com.example.back.jpa.HospitalRepository;
import com.example.back.jpa.LogisticsDRepository;
import com.example.back.jpa.RxDrugsRepository;
import com.example.back.jpa.RxMainRepository;
import com.example.back.mapper.DrugOrderMapper;
import com.example.back.service.DrugService;
import com.example.back.utils.ExcelUtils;
import com.example.back.utils.UserUtils;
import com.example.common.entity.Hospital;
import com.example.common.entity.LogisticsD;
import com.example.common.entity.RxDrugs;
import com.example.common.entity.RxMain;
import com.example.common.enums.LType;
import com.example.common.enums.PayType;
import com.example.common.support.ApiException;

import org.springframework.stereotype.Service;

import cn.hutool.core.date.DateUtil;

/**
 * @Author wxy
 * @Date 2021/1/13 14:24
 * @Version 1.0
 */
@Service
public class DrugServiceImpl implements DrugService {

    @Resource
    private DrugOrderMapper drugOrderMapper;

    @Resource
    private RxMainRepository rxMainRepository;

    @Resource
    private RxDrugsRepository rxDrugsRepository;

    @Resource
    private LogisticsDRepository logisticsDRepository;

    @Resource
    private HospitalRepository hospitalRepository;

    @Resource
    private ExcelUtils excelUtils;
    @Resource
    private UserUtils userUtils;

    /**
     * 商品订单
     */
    @Override
    public Map<String, Object> List(String orderno, String consignee, String consigneeTel, byte orderstatus, int ltype, int page, int limit) {
        int skip = (page - 1) * limit;
        if (skip < 0) skip = 0;

        List<Map<String, Object>> query = drugOrderMapper.DrugOrderList(orderno, consignee, consigneeTel, orderstatus, ltype, skip, limit);
        int count = drugOrderMapper.DrugOrderCount(orderno, consignee, consigneeTel, orderstatus, ltype);

        List<Map<String, Object>> list = new ArrayList<>();
        query.forEach(m -> {
            Map<String, Object> o = new HashMap<>();
            int iLType = 0;
            if(m.get("LType") != null)
                iLType = Long.valueOf(m.get("LType").toString()).intValue();
            o.put("RxOrderNO", m.get("RxOrderNO"));
            o.put("OrderNO", m.get("OrderNO"));
            o.put("CreateTime", m.get("CreateTime"));
            o.put("OrderPayTime", m.get("OrderPayTime") == null ? "" : m.get("OrderPayTime"));
            o.put("LType",m.get("PayType") != null ? LType.valueToDesc(iLType) : "/");
            o.put("OrderPrice", new BigDecimal(m.get("SalePrice").toString()).subtract(new BigDecimal(m.get("Freight").toString())));
            o.put("Freight", new BigDecimal(m.get("Freight").toString()));
            o.put("SalePrice", new BigDecimal(m.get("SalePrice").toString()));
            o.put("PayType",m.get("PayType") != null ? PayType.valueToDesc(Long.valueOf(m.get("PayType").toString()).intValue()) : "未支付");
            o.put("Consignee",m.get("LType") != null && iLType == 1 ? m.get("Name").toString() + "/" + m.get("Tel").toString() : "/");
            o.put("Waybill",m.get("LType") != null && iLType == 0 ? m.get("Waybill") : "/");
            int SystemStatus = Long.valueOf(m.get("SystemStatus").toString()).intValue();
            Boolean IsSend = false, IsArrive = false;
            if(m.get("IsSend") != null)
                IsSend = Boolean.valueOf(m.get("IsSend").toString());
            if(m.get("IsArrive") != null)
                IsArrive = Boolean.valueOf(m.get("IsArrive").toString());
            o.put("OrderStatus", SystemStatus  == 1 ? "待付款" :
            (SystemStatus == 2 && iLType == 0 && IsSend && !IsArrive) ? "待自提" :
            (SystemStatus == 2 && iLType == 1 && !IsSend) ? "待配送" :
            (SystemStatus == 2 && iLType == 1 && IsSend && !IsArrive) ? "待收货" :
            (SystemStatus == 2 && IsSend && IsArrive) ? "交易成功" :
            (SystemStatus == 3) ? "交易取消" : "");
            list.add(o);
        });

        Map<String, Object> res = new HashMap<>();
        res.put("list", list);
        res.put("cnt", count);
        return res;
    }

    /**
     *
     */
    @Override
    public List<Map<String, Object>> OrderExportXls(String orderno, String consignee, String consigneeTel, byte orderstatus, int ltype) {
        List<Map<String, Object>> query = drugOrderMapper.DrugOrderList(orderno, consignee, consigneeTel, orderstatus, ltype, 0, Integer.MAX_VALUE);
        DecimalFormat df = new DecimalFormat("#0.00");
        List<ExcelOrderDrug> list = new ArrayList<>();
        query.forEach(m -> {
            ExcelOrderDrug o = new ExcelOrderDrug();
            int iLType = 0;
            if(m.get("LType") != null)
                iLType = Long.valueOf(m.get("LType").toString()).intValue();
            int SystemStatus = Long.valueOf(m.get("SystemStatus").toString()).intValue();
            Boolean IsSend = false, IsArrive = false;
            if(m.get("IsSend") != null)
                IsSend = Boolean.valueOf(m.get("IsSend").toString());
            if(m.get("IsArrive") != null)
                IsArrive = Boolean.valueOf(m.get("IsArrive").toString());
            o.setRxOrderNO(m.get("RxOrderNO").toString());
            o.setOrderNO(m.get("OrderNO").toString());
            o.setCreateTime(m.get("CreateTime").toString());
            o.setOrderPayTime(m.get("OrderPayTime") == null ? "" : m.get("OrderPayTime").toString());
            o.setType(m.get("PayType") != null ? LType.valueToDesc(iLType) : "/");
            o.setOrderPrice(df.format(new BigDecimal(m.get("SalePrice").toString()).subtract(new BigDecimal(m.get("Freight").toString()))));
            o.setFreight(df.format(new BigDecimal(m.get("Freight").toString())));
            o.setSalePrice(df.format(new BigDecimal(m.get("SalePrice").toString())));
            o.setPayType(m.get("PayType") != null ? PayType.valueToDesc(Long.valueOf(m.get("PayType").toString()).intValue()) : "未支付");
            o.setConsignee(m.get("LType") != null && iLType == 1 ? m.get("Name").toString() + "/" + m.get("Tel").toString() : "/");
            o.setWaybill(m.get("LType") != null && iLType == 0 ? m.get("Waybill").toString() : "/");
            o.setOrderStatus(SystemStatus  == 1 ? "待付款" :
            (SystemStatus == 2 && iLType == 0 && IsSend && !IsArrive) ? "待自提" :
            (SystemStatus == 2 && iLType == 1 && !IsSend) ? "待配送" :
            (SystemStatus == 2 && iLType == 1 && IsSend && !IsArrive) ? "待收货" :
            (SystemStatus == 2 && IsSend && IsArrive) ? "交易成功" :
            (SystemStatus == 3) ? "交易取消" : "");

            list.add(o);
        });

        String now = DateUtil.now();
        String fileName =  "cash_" + now;
        try {
            excelUtils.excelExport(ExcelOrderDrug.class,list,fileName);
        }catch (Exception e){
            throw  new ApiException(1,e.getMessage());
        }

        return null;
    }

    /**
     * 订单详情
     */
    @Override
    public Map<String, Object> Detail(String orderno) {
        RxMain order = rxMainRepository.findById(orderno).orElseThrow(()->new ApiException(10000, "订单不存在"));
        List<RxDrugs> dlist = rxDrugsRepository.findByRxOrderNO(orderno);

        LogisticsD logistics = null;
        Map<String, Object> OrderLogistics = new HashMap<>();
        Date ArriveTime = null;
        if(order.getPayType() != null){
            logistics = logisticsDRepository.findById(orderno).orElseThrow(()->new ApiException(10000, "订单不存在"));
            if(logistics.getLType() == 0){
                Hospital hospital = hospitalRepository.findByLast();
                OrderLogistics.put("SelfAddress",  hospital.getSelfAddress());
                OrderLogistics.put("SelfName", hospital.getSelfName());
                OrderLogistics.put("ICO", hospital.getIco());
                OrderLogistics.put("Waybill", logistics.getWaybill());
                OrderLogistics.put("LType", order.getPayType() != null ? LType.valueToDesc(logistics.getLType()) : "/");
            } else if(logistics.getLType() == 1){
                OrderLogistics.put("Name", logistics.getName());
                OrderLogistics.put("Tel", logistics.getTel());
                OrderLogistics.put("Address", logistics.getAddress());
                OrderLogistics.put("Waybill", logistics.getWaybill());
                OrderLogistics.put("LType", order.getPayType() != null ? LType.valueToDesc(logistics.getLType()) : "/");
            }
            if(logistics.getIsArrive()){
                ArriveTime = logistics.getArriveTime();
            }
        }

        String OrderStatus = order.getSystemStatus() == 1 ? "待付款" :
        (order.getSystemStatus() == 2 && logistics.getLType() == 0 && logistics.getIsSend() && !logistics.getIsArrive()) ? "待自提" :
        (order.getSystemStatus() == 2 && logistics.getLType() == 1 && !logistics.getIsSend()) ? "待配送" :
        (order.getSystemStatus() == 2 && logistics.getLType() == 1 && logistics.getIsSend() && !logistics.getIsArrive()) ? "待收货" :
        (order.getSystemStatus() == 2 && logistics.getIsSend() && logistics.getIsArrive()) ? "交易成功" :
        (order.getSystemStatus() == 3) ? "交易取消" : "";

        Map<String, Object> Order = new HashMap<>();
        Order.put("RxOrderNO", order.getRxOrderNO());
        Order.put("OrderNO", order.getOrderNO());
        Order.put("OrderStatus", OrderStatus);
        Order.put("OrderPrice", order.getSalePrice().subtract(order.getFreight()));
        Order.put("Freight", order.getFreight());
        Order.put("SalePrice", order.getSalePrice());
        Order.put("PayType", order.getPayType() != null ? PayType.valueToDesc(order.getPayType()) : "未支付");
        Order.put("CreateTime", order.getCreateTime());
        Order.put("OrderPayTime", order.getOrderPayTime() != null ? order.getOrderPayTime() : "");
        Order.put("ArriveTime", ArriveTime);
        Order.put("DType", order.getDType());
        if(logistics != null && logistics.getLType() == 1 && logistics.getIsSend()){
            Order.put("SendTime", logistics.getSendTime());
        }

        Map<String, Object> res = new HashMap<>();
        res.put("Order", Order);
        res.put("OrderLogistics", OrderLogistics);

        List<Map<String, Object>> dlistm = new ArrayList<>();
        dlist.forEach(m -> {
            Map<String, Object> d = new HashMap<>();
            d.put("DrugName", m.getDrugName());
            d.put("Spec", m.getSpec());
            d.put("Price", m.getPrice());
            d.put("Num", m.getNum());
            dlistm.add(d);
        });
        res.put("dlist", dlistm);

        return res;
    }

    @Override
    public Boolean OrderSend(String orderno,String company,String companyCode,String waybill){
        LogisticsD logistics = logisticsDRepository.findById(orderno).orElseThrow(()->new ApiException(10000, "订单不存在"));
        if(logistics.getOrderType() != 1){
            throw  new ApiException(1,"不是有效的处方订单");
        }
        Date now = new Date();

        // 自提
        if(logistics.getLType() == 0){
            logistics.setIsArrive(true);
            logistics.setArriveTime(now);
            logistics.setArriveName(userUtils.getUser().getName());
        }

        // 物流
        if(logistics.getLType() == 1){
            logistics.setIsSend(true);
            logistics.setSendTime(now);
            logistics.setCompany(company);
            logistics.setCompanyCode(companyCode);
            logistics.setWaybill(waybill);
        }

        try {
            logisticsDRepository.save(logistics);
            return true;
        } catch (Exception e) {
            
        }
        return false;
    }
}
